package com.yuandengta.yomall.search.service.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.yuandengta.common.to.es.SkuEsModel;
import com.yuandengta.common.utils.JsonUtils;
import com.yuandengta.common.utils.R;
import com.yuandengta.yomall.search.config.ElasticSearchConfig;
import com.yuandengta.yomall.search.constant.EsConstant;
import com.yuandengta.yomall.search.feign.ProductFeignService;
import com.yuandengta.yomall.search.service.MallSearchService;
import com.yuandengta.yomall.search.vo.AttrResponseVO;
import com.yuandengta.yomall.search.vo.BrandResponseVO;
import com.yuandengta.yomall.search.vo.SearchParamVO;
import com.yuandengta.yomall.search.vo.SearchResponseVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 商品检索服务 {@link MallSearchServiceImpl}
 *
 * @author Kevin
 * @email: 178676392@qq.com
 */
@Slf4j
@Service
public class MallSearchServiceImpl implements MallSearchService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private ProductFeignService productFeignService;

    /**
     * 商品检索
     * @param searchParamVO 检索的所有参数
     * @return
     */
    @Override
    public SearchResponseVO search(SearchParamVO searchParamVO) {
        SearchResponseVO searchResponseVO = null;

        // 1.准备ES检索请求
        SearchRequest searchRequest = buildSearchRequest(searchParamVO);

        try {
            // 2.执行检索请求
            SearchResponse searchResponse = restHighLevelClient.search(searchRequest, ElasticSearchConfig.COMMON_OPTIONS);
            // 3.分析检索结果，封装成SearchResponseVO
            searchResponseVO = buildSearchResponse(searchResponse, searchParamVO);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return searchResponseVO;
    }

    /**
     * 准备检索请求
     *  模糊匹配 must
     *  过滤 filter
     *  排序 sort
     *  分页 from size
     *  高亮 highlight
     *  聚合分析 aggs
     * @return
     */
    private SearchRequest buildSearchRequest(SearchParamVO param) {
        // 动态构建检索的DSL语句
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        // 查询：模糊匹配、过滤（品牌、分类、属性、价格区间、库存）
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        // 按照商品名称模糊查询
        if (!StringUtils.isEmpty(param.getKeyword())) {
            boolQuery.must(QueryBuilders.matchQuery("skuTitle", param.getKeyword()));
        }
        // 按照三级分类id查询
        if (param.getCatalog3Id() != null) {
            boolQuery.filter(QueryBuilders.termQuery("catalogId", param.getCatalog3Id()));
        }
        // 按照品牌id查询
        if (param.getBrandId() != null && param.getBrandId().size() > 0) {
            boolQuery.filter(QueryBuilders.termsQuery("brandId", param.getBrandId()));
        }
        // 按照所有指定的属性进行查询
        // attr=1_3G:4G:5G&attr=2_高通骁龙845
        if (param.getAttrs() != null && param.getAttrs().size() > 0) {
            for (String attr : param.getAttrs()) {
                String[] s = attr.split("_");
                String attrId = s[0];
                String[] attrValues = s[1].split(":");

                BoolQueryBuilder query = QueryBuilders.boolQuery();
                query.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                query.must(QueryBuilders.termsQuery("attrs.attrValue", attrValues));
                // 每一个属性都必须生成一个 NestedQuery
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", query, ScoreMode.None);
                boolQuery.filter(nestedQuery);
            }
        }
        // 按照是否有库存进行查询
        if (param.getHasStock() != null) {
            boolQuery.filter(QueryBuilders.termQuery("hasStock", param.getHasStock() == 1));
        }
        // 按照价格区间进行查询：1_100/_100/100_
        if (!StringUtils.isEmpty(param.getSkuPrice())) {
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
            String[] price = param.getSkuPrice().split("_", 2);
            if (StringUtils.isEmpty(price[0])) {
                rangeQuery.lte(price[1]);
            } else if (StringUtils.isEmpty(price[1])) {
                rangeQuery.gte(price[0]);
            } else {
                rangeQuery.gte(price[0]).lte(price[1]);
            }
            boolQuery.filter(rangeQuery);
        }

        searchSourceBuilder.query(boolQuery);

        // 排序
        // sort=saleCount_desc
        if (!StringUtils.isEmpty(param.getSort())) {
            String[] s = param.getSort().split("_");
            SortOrder sortOrder = s[1].equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC;
            if ("price".equals(s[0])) {
                searchSourceBuilder.sort("skuPrice", sortOrder);
            } else {
                searchSourceBuilder.sort(s[0], sortOrder);
            }
        }

        // 分页
        // from = (pageNum - 1) * pageSize
        searchSourceBuilder.from((param.getPageNum() - 1) * EsConstant.PRODUCT_PAGE_SIZE);
        searchSourceBuilder.size(EsConstant.PRODUCT_PAGE_SIZE);

        // 高亮
        if (!StringUtils.isEmpty(param.getKeyword())) {
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            searchSourceBuilder.highlighter(highlightBuilder);
        }

        // 聚合分析
        // 品牌聚合
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg").field("brandId").size(50);
        // 品牌子聚合
        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        searchSourceBuilder.aggregation(brand_agg);
        // 分类聚合
        TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg").field("catalogId").size(20);
        catalog_agg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));
        searchSourceBuilder.aggregation(catalog_agg);
        // 属性聚合
        NestedAggregationBuilder attr_agg = AggregationBuilders.nested("attr_agg", "attrs");
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId").size(1);
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(50));
        attr_agg.subAggregation(attr_id_agg);
        searchSourceBuilder.aggregation(attr_agg);

        System.out.println("构建DSL：" + searchSourceBuilder.toString());

        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, searchSourceBuilder);
        return searchRequest;
    }

    /**
     * 返回检索结果数据
     * @param searchResponse
     * @return
     */
    private SearchResponseVO buildSearchResponse(SearchResponse searchResponse, SearchParamVO param) {
        SearchResponseVO searchResponseVO = new SearchResponseVO();

        // 返回所有查询到的商品
        SearchHits hits = searchResponse.getHits();
        List<SkuEsModel> skuEsModels = new ArrayList<>();
        if (hits.getHits() != null && hits.getHits().length > 0) {
            for (SearchHit hit : hits.getHits()) {
                String sourceAsString = hit.getSourceAsString();
                SkuEsModel skuEsModel = JsonUtils.jsonToPojo(sourceAsString, SkuEsModel.class);
                // 设置关键字高亮
                if (!StringUtils.isEmpty(param.getKeyword())) {
                    String skuTitle = hit.getHighlightFields().get("skuTitle").getFragments()[0].string();
                    skuEsModel.setSkuTitle(skuTitle);
                }
                skuEsModels.add(skuEsModel);
            }
        }
        searchResponseVO.setProducts(skuEsModels);

        // 聚合分析：分类信息、品牌信息、属性信息
        // 分类信息
        List<SearchResponseVO.CatalogVO> catalogVOS = new ArrayList<>();
        ParsedLongTerms catalog_agg = searchResponse.getAggregations().get("catalog_agg");
        for (Terms.Bucket bucket : catalog_agg.getBuckets()) {
            SearchResponseVO.CatalogVO catalogVO = new SearchResponseVO.CatalogVO();
            // 分类ID
            catalogVO.setCatalogId(Long.parseLong(bucket.getKeyAsString()));
            // 分类名
            ParsedStringTerms catalog_name_agg = bucket.getAggregations().get("catalog_name_agg");
            String catalogName = catalog_name_agg.getBuckets().get(0).getKeyAsString();
            catalogVO.setCatalogName(catalogName);

            catalogVOS.add(catalogVO);
        }
        searchResponseVO.setCatalogs(catalogVOS);
        // 品牌信息
        List<SearchResponseVO.BrandVO> brandVOS = new ArrayList<>();
        ParsedLongTerms brand_agg = searchResponse.getAggregations().get("brand_agg");
        for (Terms.Bucket bucket : brand_agg.getBuckets()) {
            SearchResponseVO.BrandVO brandVO = new SearchResponseVO.BrandVO();
            // 品牌ID
            brandVO.setBrandId(bucket.getKeyAsNumber().longValue());
            // 品牌名称
            ParsedStringTerms brand_name_agg = bucket.getAggregations().get("brand_name_agg");
            String brandName = brand_name_agg.getBuckets().get(0).getKeyAsString();
            brandVO.setBrandName(brandName);
            // 品牌图片
            ParsedStringTerms brand_img_agg = bucket.getAggregations().get("brand_img_agg");
            String brandImg = brand_img_agg.getBuckets().get(0).getKeyAsString();
            brandVO.setBrandImg(brandImg);

            brandVOS.add(brandVO);
        }
        searchResponseVO.setBrands(brandVOS);
        // 属性
        List<SearchResponseVO.AttrVO> attrVOS = new ArrayList<>();
        ParsedNested attr_agg = searchResponse.getAggregations().get("attr_agg");
        ParsedLongTerms attr_id_agg = attr_agg.getAggregations().get("attr_id_agg");
        for (Terms.Bucket bucket : attr_id_agg.getBuckets()) {
            SearchResponseVO.AttrVO attrVO = new SearchResponseVO.AttrVO();
            // 属性ID
            long attrId = bucket.getKeyAsNumber().longValue();
            attrVO.setAttrId(attrId);
            // 属性名
            String attrName = ((ParsedStringTerms) bucket.getAggregations().get("attr_name_agg"))
                    .getBuckets().get(0).getKeyAsString();
            attrVO.setAttrName(attrName);
            // 属性所有值
            List<String> attrValues = ((ParsedStringTerms) bucket.getAggregations().get("attr_value_agg"))
                    .getBuckets().stream().map(item -> {
                        String keyAsString = item.getKeyAsString();
                        return keyAsString;
                    }).collect(Collectors.toList());
            attrVO.setAttrValues(attrValues);
            attrVOS.add(attrVO);
        }
        searchResponseVO.setAttrs(attrVOS);

        // 分页信息
        // 当前页码
        searchResponseVO.setPageNum(param.getPageNum());
        // 总记录数
        long totalCount = hits.getTotalHits().value;
        searchResponseVO.setTotalCount(totalCount);
        // 总页数
        int totalPage = (int)totalCount % EsConstant.PRODUCT_PAGE_SIZE == 0
                ? (int)totalCount / EsConstant.PRODUCT_PAGE_SIZE
                : (int)totalCount / EsConstant.PRODUCT_PAGE_SIZE + 1;
        searchResponseVO.setTotalPage(totalPage);
        // 页码导航数
        List<Integer> pageNavs = new ArrayList<>();
        for (int i = 1; i <= totalPage; i++) {
            pageNavs.add(i);
        }
        searchResponseVO.setPageNavs(pageNavs);

        // 构建面包屑导航
        // 面包屑-属性
        if (param.getAttrs() != null && param.getAttrs().size() > 0) {
            List<SearchResponseVO.NavVO> navs = param.getAttrs().stream().map(attr -> {
                SearchResponseVO.NavVO navVO = new SearchResponseVO.NavVO();
                String[] s = attr.split("_");
                searchResponseVO.getAttrIds().add(Long.parseLong(s[0]));
                navVO.setNavValue(s[1]);

                // 远程调用耗时，远程查询接口结果加入缓存
                R r = productFeignService.getAttrInfo(Long.parseLong(s[0]));
                if (r.getCode() == 0) {
                    AttrResponseVO data = r.getData("attr", new TypeReference<AttrResponseVO>() {});
                    navVO.setNavName(data.getAttrName());
                } else {
                    log.error("调用远程服务 yomall-product 查询属性信息失败");
                    navVO.setNavName("");
                }

                // 取消面包屑以后，需要将请求url里面的当前属性值置空
                String replace = replaceQueryString(param.getQueryString(), "attrs", attr);
                navVO.setLink("http://search.yomall.com/list.html?" + replace);

                return navVO;
            }).collect(Collectors.toList());
            searchResponseVO.setNavs(navs);
        }

        // 面包屑-品牌
        if (param.getBrandId() != null && param.getBrandId().size() > 0) {
            List<SearchResponseVO.NavVO> navs = searchResponseVO.getNavs();
            SearchResponseVO.NavVO navVO = new SearchResponseVO.NavVO();
            navVO.setNavName("品牌");

            // 远程调用耗时，远程查询接口结果加入缓存
            R r = productFeignService.getBrandInfos(param.getBrandId());
            if (r.getCode() == 0) {
                List<BrandResponseVO> brands = r.getData("brands", new TypeReference<List<BrandResponseVO>>() {});
                String replace = null;
                StringBuffer buffer = new StringBuffer();
                for (int i = 0; i < brands.size(); i++) {
                    BrandResponseVO vo = brands.get(i);
                    if (i == 0) {
                        buffer.append(vo.getName());
                    } else {
                        buffer.append("、" + vo.getName());
                    }
                    replace = replaceQueryString(param.getQueryString(), "brandId", vo.getBrandId()+"");
                }
                navVO.setNavValue(buffer.toString());
                navVO.setLink("http://search.yomall.com/list.html?" + replace);
            } else {
                log.error("调用远程服务 yomall-product 查询品牌信息失败");
            }
            navs.add(navVO);
        }

        // TODO:面包屑-分类

        return searchResponseVO;
    }

    private String replaceQueryString(String queryString, String key, String value) {
        String encodeValue = null;
        try {
            encodeValue = URLEncoder.encode(value, "UTF-8");
            // java 对于空格编码为 +
            // 浏览器 对于空格编码为 20%
            encodeValue = encodeValue.replace("+", "%20");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String replace = queryString.replace("&"+key+"=" + encodeValue, "");
        return replace;
    }
}
